/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iddskeygenerator;

import Main.Parameters;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import plugin.SystemInterface;
import system.MessageOUTPUT;

/**
 *
 * @author ZeM
 */
public class keygenerator implements SystemInterface {

    static int PreviousInputUserLib;
    static int stage; //0 - start 1 - name received
    static String name;
    static int priority;

    public void start() {
        //save previous number of lib that was using input stream
        stage = 0;
        PreviousInputUserLib = Parameters.LibConsoleInputReceiver;
        int counter = 0;
        boolean find = false;
        do {
            if (Parameters.RunningLibs[counter].equals("iddsKeyGenerator")) {
                find = true;
                Parameters.LibConsoleInputReceiver = counter;
            } else {
                counter++;
            }
        } while (counter < Parameters.RunningLibs.length & !find);


        //Message output: "Please enter user name"
        new MessageOUTPUT().OutputToCUIWithoutLogging(new MessageOUTPUT().Message("s0001", null));
    }

    public void interrupt() {
    }

    public void pause() {
    }

    public void play() {
    }

    public void input(String message) {
        //getting name
        if (stage == 0) {
            name = message;
            stage = 1;
            //Message output: "Please enter user priority"
            new MessageOUTPUT().OutputToCUIWithoutLogging(new MessageOUTPUT().Message("s0004", null));
        }
        //getting priority
        if (stage == 1) {
            priority = Byte.parseByte(message);
            stage = 0;
            CreateKey();
            //return previous console receiver;
            Parameters.LibConsoleInputReceiver = PreviousInputUserLib;

        }

    }

    void CreateKey() {
        File key = new File("key");
        key.mkdirs();
        try {

            FileOutputStream fos = new FileOutputStream("key" + File.separatorChar + name + ".key");
            DataOutputStream dos = new DataOutputStream(fos);

            dos.write((byte)0x0A); //first byte - just
            dos.write(priority); //second byte priority
            

            Random generator = new Random();
            byte[] bytecode = new byte[128];
            generator.nextBytes(bytecode);
            dos.write(bytecode);


            dos.flush();
            dos.close();
            fos.close();
            new MessageOUTPUT().OutputToCUIWithoutLogging(new MessageOUTPUT().Message("ev0013", null));
        } catch (IOException ex) {
        }


    }
}
